package cn.echisan.homework.controller;

import cn.echisan.homework.enums.Role;
import cn.echisan.homework.model.User;
import cn.echisan.homework.service.UserService;
import cn.echisan.homework.validator.LoginCheck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by echisan on 2018/5/29
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @GetMapping
    public String login() {
        return "index";
    }

    @PostMapping
    public String login(@Validated(LoginCheck.class) User user, BindingResult bindingResult, Model model, HttpSession session) {

        if (bindingResult.hasErrors()) {
            List<String> errors = new ArrayList<>();
            bindingResult.getAllErrors().forEach(objectError -> errors.add(objectError.getDefaultMessage()));
            model.addAttribute("errors", errors);
            return "index";
        }

        User user1 = userService.getUserByIdentifyNum(user.getIdentifyNum());
        if (user1 != null) {
            if (user1.getPassword().equals(user.getPassword())) {
                session.setAttribute("user",user1);
                return "redirect:home";
            }else {
                model.addAttribute("errors", Collections.singleton("密码不正确"));
                return "index";
            }
        }

        model.addAttribute("errors", Collections.singleton("该账号不存在"));
        return "index";
    }
}
